package lib

//link to 516
func init() {
	Probs = append(Probs, Problem{
		Num:         5,
		Discription: "最长回文子串",
		Level:       2,
		Labels: map[string]int{
			"双指针滑动": 1,
			"奇偶性":   1,
			"动态规划":  1,
		},
	})
}

func LongestPalindrome2(s string) string {
	n := len(s)
	dp := make([][]bool, n)
	for i := range dp {
		dp[i] = make([]bool, n+1)
		//判断s[i-1]==s[i+1]后需要这种情况
		dp[i][i] = true
		dp[i][i+1] = true
	}

	maxStart := 0
	maxEnd := 1
	for i := n - 1; i >= 0; i-- {
		for j := i + 2; j <= n; j++ {
			dp[i][j] = s[i] == s[j-1] && dp[i+1][j-1]
			if dp[i][j] && j-i > maxEnd-maxStart {
				maxEnd = j
				maxStart = i
			}
		}
	}

	return s[maxStart:maxEnd]
}

func LongestPalindrome(s string) string {
	byteArray := []byte(s)
	if len(byteArray) == 1 {
		return s
	}

	longestStart := 0
	longestEnd := 0
	for i := 1; i < len(byteArray); i++ {
		start1, end1 := getOdd(byteArray, i)
		start2, end2 := getEven(byteArray, i)
		var longerStart, longerEnd int
		if (end1 - start1) >= (end2 - start2) {
			longerStart = start1
			longerEnd = end1
		} else {
			longerStart = start2
			longerEnd = end2
		}
		if (longerEnd - longerStart) > (longestEnd - longestStart) {
			longestStart = longerStart
			longestEnd = longerEnd
		}
	}

	return string(byteArray[longestStart : longestEnd+1])
}

func getOdd(array []byte, center int) (int, int) {
	i := center - 1
	j := center + 1
	if i < 0 || j >= len(array) {
		return center, center
	}

	for {
		if array[i] == array[j] {
			i--
			j++
		} else {
			i++
			j--
			return i, j
		}

		if i < 0 || j >= len(array) {
			i++
			j--
			return i, j
		}
	}
}

func getEven(array []byte, right int) (int, int) {
	i := right - 1
	j := right
	for {
		if array[i] == array[j] {
			i--
			j++
		} else {
			i++
			j--
			return i, j
		}

		if i < 0 || j >= len(array) {
			i++
			j--
			return i, j
		}
	}
}
